package com.atguigu.chapter13;

import com.atguigu.bean.UserBehavior;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.TypeHint;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.shaded.guava18.com.google.common.hash.BloomFilter;
import org.apache.flink.shaded.guava18.com.google.common.hash.Funnels;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.Date;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/7/21 14:17
 */
public class Flink03_UV_Bloom {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(2);
        
        env
            .readTextFile("input/UserBehavior.csv")
            .map(line -> { // 对数据切割, 然后封装到POJO中
                String[] split = line.split(",");
                return new UserBehavior(Long.valueOf(split[0]), Long.valueOf(split[1]), Integer.valueOf(split[2]), split[3], Long.parseLong(split[4]) * 1000);
            })
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<UserBehavior>forBoundedOutOfOrderness(Duration.ofSeconds(5))
                    .withTimestampAssigner((element, recordTimestamp) -> element.getTimestamp())
            )
            .filter(behavior -> "pv".equals(behavior.getBehavior()))
            .keyBy(UserBehavior::getBehavior)
            .window(TumblingEventTimeWindows.of(Time.hours(1)))
            .process(new ProcessWindowFunction<UserBehavior, String, String, TimeWindow>() {
    
                private ValueState<BloomFilter<Long>> bfState;
                private ValueState<Long> sumState;
    
                @Override
                public void open(Configuration parameters) throws Exception {
                    sumState = getRuntimeContext()
                        .getState(new ValueStateDescriptor<Long>("sumState", Long.class));
    
                    bfState = getRuntimeContext()
                        .getState(new ValueStateDescriptor<BloomFilter<Long>>("bfState", TypeInformation.of(new TypeHint<BloomFilter<Long>>() {})));
                }
                
                @Override
                public void process(String key,
                                    Context ctx,
                                    Iterable<UserBehavior> elements,
                                    Collector<String> out) throws Exception {
                    sumState.clear();
                    bfState.clear();
                    
                    sumState.update(0L);
                    bfState.update(BloomFilter.create(Funnels.longFunnel(), 10000000, 0.01));
                    
                    long sum = sumState.value();
                    BloomFilter<Long> bf = bfState.value();
                    
                    for (UserBehavior ub : elements) {
                        
                        if (bf.put(ub.getUserId())) {
                            sum++; // 这次存储的时候元素不存在才算一个新的uid
                        }
                    }
                    out.collect("窗口开始: " + new Date(ctx.window().getStart()) +
                                    ", 窗口结束: " + new Date(ctx.window().getEnd()) +
                                    "uv:" + sum
                    );
                    
                }
            })
            .print();
        
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
